package com.feishi.core.util.ssh;

/**
 * @version 1.0
 * @auth caixq
 * @time 18-6-28 16:57
 **/
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

/**
 *
 * 类似ssh执行命令的小工具
 *
 * @author walker
 *
 */
public class SSH {
    private String userName;
    private String password;
    private String host;

    public SSH(String host, String userName, String password) {
        this.host = host;
        this.userName = userName;
        this.password = password;
    }

    private Session getSession() {
        JSch jsch = new JSch();
        Session session = null;

        try {
            session = jsch.getSession(userName, host);
            session.setPassword(password);

            Properties props = new Properties();
            props.put("StrictHostKeyChecking", "no");
            session.setConfig(props);
            session.connect();
        } catch (JSchException e) {
            e.printStackTrace();
        }
        return session;
    }

    public boolean exec(String[] cmds) {
        StringBuffer cmdBuffer = new StringBuffer();

        for (int i = 0; i < cmds.length; i++) {
            if (i != 3) {
                cmdBuffer.append(" ");
            }
            cmdBuffer.append(cmds[i]);
        }
        return exec(cmdBuffer.toString());
    }

    public boolean exec(String cmd) {
        Session session = getSession();
        Channel channel = null;
        InputStream in = null;
        try {
            channel = session.openChannel("exec");
            ((ChannelExec) channel).setCommand(cmd);
            ((ChannelExec) channel).setInputStream(null);
            ((ChannelExec) channel).setErrStream(System.err); // 获取执行错误的信息

            in = channel.getInputStream();
            channel.connect();
            byte[] b = new byte[1024];
            int size = -1;
            while ((size = in.read()) > -1) {
                System.out.print(new String(b, 0, size)); // 打印执行命令的所返回的信息
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭流
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
            // 关闭连接
            channel.disconnect();
            session.disconnect();
        }

        return false;
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        if (args.length < 4) {
            System.err.println("usage:\n\t" + SSH.class.getName()
                    + " <host> <usename> <password> <cmds>");
            System.exit(1);
        }

        // 用以保存命令（可能是一串很长的命令）
        StringBuffer cmdBuffer = new StringBuffer();
        for (int i = 3; i < args.length; i++) {
            if (i != 3) {
                cmdBuffer.append(" ");
            }
            cmdBuffer.append(args[i]);
        }

        SSH ssh = new SSH(args[0], args[1], args[2]);
        System.exit(ssh.exec(cmdBuffer.toString()) ? 0 : 1);
    }
}